#include "iconswitcher.h"
#include <QFile>
#include <QTextStream>
#include <QStringList>
#include <QDebug>

namespace {
//    const QString DESKTOP("/usr/share/applications/2g3g_app_harmattan.desktop");
    const QString DESKTOP("/opt/2g3g_app/2g3g_app_harmattan.desktop");
    const QString NEW_DESKTOP("/home/user/.local/share/applications/2g3g_app_harmattan.desktop");
    const QString ICON_2G("/usr/share/icons/hicolor/80x80/apps/2g3g_2g.png");
    const QString ICON_3G("/usr/share/icons/hicolor/80x80/apps/2g3g_3g.png");
    const QString ICON_DUAL("/usr/share/icons/hicolor/80x80/apps/2g3g_dual.png");
}




IconSwitcher::IconSwitcher() :
        desktop(DESKTOP),
        newdesktop(NEW_DESKTOP)
{

}




void IconSwitcher::setIcon2G()
{
    QStringList lines;
    if ( !readFile(lines) ) return;
    lines.replaceInStrings(QRegExp("^Icon=.*"), "Icon="+ICON_2G);
    writeFile(lines);
}

void IconSwitcher::setIcon3G()
{
    QStringList lines;
    if ( !readFile(lines) ) return;
    lines.replaceInStrings(QRegExp("^Icon=.*"), "Icon="+ICON_3G);
    writeFile(lines);
}

void IconSwitcher::setIconDual()
{
    QStringList lines;
    if ( !readFile(lines) ) return;
    lines.replaceInStrings(QRegExp("^Icon=.*"), "Icon="+ICON_DUAL);
    writeFile(lines);
}

void IconSwitcher::createIcon() {
    QStringList lines;
    if ( !readFile(lines) ) return;
    writeFile(lines);
}




bool IconSwitcher::readFile(QStringList &lines)
{
    if (!desktop.open(QIODevice::ReadOnly | QIODevice::Text))
        return false;

    QTextStream in(&desktop);
    while (!in.atEnd())
        lines += in.readLine();

    desktop.close();
    return true;
}

bool IconSwitcher::writeFile(const QStringList &lines)
{
    if (!newdesktop.open(QIODevice::WriteOnly | QIODevice::Text))
        return false;

    QTextStream out(&newdesktop);
    foreach(const QString &line, lines)
        out << line << endl;

    newdesktop.close();
    return true;
}
